package com.imooc.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.IContext;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import com.imooc.domain.MiaoshaUser;
import com.imooc.redis.GoodsKey;
import com.imooc.redis.RedisService;
import com.imooc.result.Result;
import com.imooc.service.GoodsService;
import com.imooc.service.MiaoshaUserService;
import com.imooc.vo.GoodsDetailVo;
import com.imooc.vo.GoodsVo;

@Controller
@RequestMapping("/goods")
public class GoodsController {
	
	@Autowired
	MiaoshaUserService userService;
	
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	RedisService redisService;
	
	@Autowired
	ApplicationContext applicationContext;
	
	@Autowired
	ThymeleafViewResolver thymeleafViewResolver;

//	@RequestMapping("/to_list")
//	public String goodsList(HttpServletResponse response, Model model, MiaoshaUser user){
//		model.addAttribute("user", user);
//		// 查询秒杀的商品列表
//		List<GoodsVo> goodsList = goodsService.listGoodsVo();
//		model.addAttribute("goodsList", goodsList);
//		return "goods_list";
//	}
	
	/**
	 * 商品列表页  - 页面缓存
	 * @return
	 */
	@RequestMapping(value="/to_list", produces="text/html")
	@ResponseBody
	public String goodsList(HttpServletResponse response,
			HttpServletRequest request,
			Model model, 
			MiaoshaUser user){
		model.addAttribute("user", user);
		// 查询秒杀的商品列表
		List<GoodsVo> goodsList = goodsService.listGoodsVo();
		model.addAttribute("goodsList", goodsList);
		// 获取缓存
		String html = redisService.get(GoodsKey.GET_GOODS_LIST, "", String.class);
		if(StringUtils.isNotEmpty(html)){
			return html;
		}
		//手动渲染
		html = manualRender(response, request, model, GoodsKey.GET_GOODS_LIST, "", "goods_list");
		return html;
	}
	
	
	
//	@RequestMapping("/to_detail/{goodsId}")
//	public String goodsDetail(HttpServletResponse response,
//			Model model,
//			MiaoshaUser user,
//			@PathVariable("goodsId") Long goodsId){
//		model.addAttribute("user", user);
//		
//		GoodsVo goods = goodsService.getGoodsByGoodsId(goodsId);
//		model.addAttribute("goods", goods);
//		//计算秒杀时间
//		long start = goods.getStartDate().getTime();
//		long end = goods.getEndDate().getTime();
//		long now = System.currentTimeMillis();
//		
//		int miaoshaStatus = 0; // 秒杀未开始
//		int remainSeconds = 0;
//		
//		if(now < start){
//			//秒杀未开始
//			miaoshaStatus = 0;
//			remainSeconds = (int)(start - now)/1000;
//		}else if(now > end){
//			//秒杀已结束
//			miaoshaStatus = 2;
//			remainSeconds = -1;
//		}else{
//			//秒杀进行中
//			miaoshaStatus = 1;
//			remainSeconds = 0;
//		}
//		model.addAttribute("miaoshaStatus", miaoshaStatus);
//		model.addAttribute("remainSeconds", remainSeconds);
//		return "goods_detail";
//	}
	
	/**
	 * URL缓存
	 * @param response
	 * @param model
	 * @param user
	 * @param goodsId
	 * @return
	 */
	@RequestMapping(value="/to_detail/{goodsId}", produces="text/html")
	@ResponseBody
	public String goodsDetail(HttpServletResponse response,
			HttpServletRequest request,
			Model model,
			MiaoshaUser user,
			@PathVariable("goodsId") long goodsId){
		model.addAttribute("user", user);
		
		// 获取缓存
		String html = redisService.get(GoodsKey.GET_GOODS_DETAIL, "" + goodsId, String.class);
		if(StringUtils.isNotEmpty(html)){
			return html;
		}
		
		GoodsVo goods = goodsService.getGoodsByGoodsId(goodsId);
		model.addAttribute("goods", goods);
		//计算秒杀时间
		long start = goods.getStartDate().getTime();
		long end = goods.getEndDate().getTime();
		long now = System.currentTimeMillis();
		
		int miaoshaStatus = 0; // 秒杀未开始
		int remainSeconds = 0;
		
		if(now < start){
			//秒杀未开始
			miaoshaStatus = 0;
			remainSeconds = (int)(start - now)/1000;
		}else if(now > end){
			//秒杀已结束
			miaoshaStatus = 2;
			remainSeconds = -1;
		}else{
			//秒杀进行中
			miaoshaStatus = 1;
			remainSeconds = 0;
		}
		model.addAttribute("miaoshaStatus", miaoshaStatus);
		model.addAttribute("remainSeconds", remainSeconds);
//		return "goods_detail";
		
		//手动渲染
		html = manualRender(response, request, model ,GoodsKey.GET_GOODS_DETAIL, ""+goodsId, "goods_detail");
		return html;
	}

	
	 @RequestMapping(value="/detail/{goodsId}")
	    @ResponseBody
	    public Result<GoodsDetailVo> detail(HttpServletRequest request, HttpServletResponse response, Model model,MiaoshaUser user,
	    		@PathVariable("goodsId")long goodsId) {
	    	GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
	    	long startAt = goods.getStartDate().getTime();
	    	long endAt = goods.getEndDate().getTime();
	    	long now = System.currentTimeMillis();
	    	int miaoshaStatus = 0;
	    	int remainSeconds = 0;
	    	if(now < startAt ) {//秒杀还没开始，倒计时
	    		miaoshaStatus = 0;
	    		remainSeconds = (int)((startAt - now )/1000);
	    	}else  if(now > endAt){//秒杀已经结束
	    		miaoshaStatus = 2;
	    		remainSeconds = -1;
	    	}else {//秒杀进行中
	    		miaoshaStatus = 1;
	    		remainSeconds = 0;
	    	}
	    	GoodsDetailVo vo = new GoodsDetailVo();
	    	vo.setGoods(goods);
	    	vo.setUser(user);
	    	vo.setRemainSeconds(remainSeconds);
	    	vo.setMiaoshaStatus(miaoshaStatus);
	    	return Result.success(vo);
	    }
	    


	private String manualRender(HttpServletResponse response, HttpServletRequest request, Model model, GoodsKey prefix, String key, String... params) {
		String html=null, markTemplateName=null;
		if(params != null && params.length >= 0){
			markTemplateName = params[0];
		}
		
		SpringWebContext context = new SpringWebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap(), applicationContext);
		html = thymeleafViewResolver.getTemplateEngine().process(markTemplateName, context);
		if(StringUtils.isNotEmpty(html)){
			redisService.set(prefix, key, html);
		}
		return html;
	}
	
	
	
	
	
}
